---
title: "STAT2 Lecture Slides Section 1.1"
author: "Oliver d'Pug"
highlight-style: pygments
format:
  html: 
    code-fold: false
    html-math-method: katex
  pdf:
    geometry: 
      - top=30mm
      - left=30mm
  docx: default
---

```{r, setup}
  ### Load the pacman package, or install and load on failure
  if (!require(pacman)){
    install.packages("pacman")
    library(pacman)
  }
  p_load(mosaic)
```

## Fitting a Constant (Mean) Model

The data are in the ***MidtermFinal.csv*** file which resides in the ***Datasets*** folder.  We read this file to create a dataframe.

```{r, read_MidtermFinal}
  MidtermFinal = read.csv("Datasets/MidtermFinal.csv")
  head(MidtermFinal)
```

Computing the mean is easy since there is a function **mean**.

```{r, mean_final}
  mean(MidtermFinal$Final)
  (Final.mean = mean(MidtermFinal$Final))
```

We can plot **Final** as a function of **Midterm** and add the mean of **Final** as a horizontal line.

```{r, plot_final_midterm}
  plot(Final~Midterm, data=MidtermFinal)
  abline(h=Final.mean, col="maroon")
```  

## Fitting a Least Squares Model

Again, the data are in the ***MidtermFinal.csv*** file.  Since the file was read above, we need only check that the dataframe that was created above exists.

```{r, check_MidtermFinal}
  ls()
  head(MidtermFinal)
```

We see that the dataframe **MidtermFinal** and the mean of the **Final** variable, **Final.mean**, both exist.  This can also be seen in the ***Environment*** tab at the upper right in ***RStudio***.

We now fit the least squares linear regression model.

```{r, ls_final_midterm}
  lm(Final~Midterm, data=MidtermFinal)
```  

The model can be saved for later use. The extra parentheses request a display of the result, while  **summary* requests more detailed output.

```{r, lm_final_midterm}
  (Final.lm = lm(Final~Midterm, data=MidtermFinal))
  summary(Final.lm)
```

A plot with the regression line can be created quite easily.

```{r, final_plot_with_lm}
  plot(Final~Midterm, data=MidtermFinal)
  abline(Final.lm, col="green", lty=2)
```